package com.way.service;

import com.way.domain.entity.SysUser;
import com.way.repository.SysUserRepository;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private SysUserRepository userRepository;

    @Override

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<SysUser> userOptional = userRepository.findByUsername(username);
        if (userOptional.isEmpty()) {
            throw new UsernameNotFoundException("用户不存在");
        }
        SysUser user = userOptional.get();

        return User
                .withUsername(user.getUsername())
                .password(user.getPassword())
                .roles(user.getRole().split(","))
                .build();
    }

}
